#include "server.h"
#include "client.h"
#include "socket.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <iostream>
using namespace std;

//   Copyright 2011 CPIR Team
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

int32_t port = 9888;
int server_msg_num = 100;
int chos = 2;
void serverProc()
{	
	cout<<endl<<"Server starting......"<<endl;
	cout<<"Input the size of message server has:"<<endl;
	cin>>server_msg_num;
    MessageCollection* msg = MessageCollection::fromRandom(server_msg_num);	
    RabinServer server(msg,port);	
	cout<<"Server has "<<server_msg_num<<" message"<<endl;
	cout<<"Client should recieve: "<<(msg->get(chos-1))->getData()<<endl;
    server.run();
    delete msg;
}

void clientProc(char *host_addr)
{
	cout<<endl<<"Client starting......"<<endl;
    RabinClient client(host_addr, port);	
	if (!(client.get_conn_succ())) {
		cout<<"connect fail"<<endl;
		return;
	}
	cout<<"connect successfully"<<endl;	
    clock_t start,end;
	start = clock();
    Message* msg = client.get(chos-1);	
	end = clock();
	double time = double(end - start);   
	cout<<"transfer time is: "<<time<<endl; 
	cout<<"client get "<<msg->getData()<<endl;
    delete msg;
}

int main(int argc, char* argv[])
{
	if (argc < 2) {
		cout<<"usage:"<<endl<<"server"<<endl<<"client host_name";
		return 0;
	}
	if (strcmp(argv[1],"client") == 0) {		
		clientProc(argv[2]);
	}
	else if (strcmp(argv[1],"server") == 0) {
		serverProc();
	}	
}